package com.cj.framework.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import com.cj.framework.app.BaseApplication;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by cj on 2016/6/4.
 * Email:781806481@qq.com
 */
public class FileUtils {
    private static final String TAG="FileUtils";
    private static final String CHARSET="UTF-8";

    private static String innerFileDir = BaseApplication.getContext().getFilesDir().getAbsolutePath();
    private static String innerCacheDir =BaseApplication.getContext().getCacheDir().getAbsolutePath();
    private static String sdCacheDir =BaseApplication.getContext().getExternalCacheDir().getAbsolutePath();
    private static String sdDir= Environment.getExternalStorageDirectory().getAbsolutePath();
    /**
     * 将数据保存到/data/data/packagename/files中
     * @param fileName
     * @param data
     */
    public static void saveToInnerFiles(String fileName,String data,boolean append){
        String filePath= innerFileDir +File.separator+fileName;
        save(filePath,data,append);
    }

    /**
     * 将文件保存到/data/data/packagename/cache中
     * @param fileName
     * @param data
     */
    public static void saveToInnerCache(String fileName,String data){
        String filePath= innerCacheDir +File.separator+fileName;
        save(filePath,data,false);
    }

    /**
     * 将文件保存到/sdcard/0/android/data/packagename/cache中
     * @param fileName
     * @param data
     */
    public static void saveToSDCache(String fileName,String data){
        String filePath= sdCacheDir +File.separator+fileName;
        save(filePath,data,false);
    }

    /**
     * 将文件保存到sdcard指定目录中
     * @param fileDir
     * @param fileName
     * @param data
     * @param append
     */
    public static void saveToSDFile(String fileDir,String fileName,String data,boolean append){
        //创建目录，避免输出流初始化失败
        File dir=new File(sdDir+File.separator+fileDir);
        if(!dir.exists()){
            dir.mkdirs();
        }

        save(dir.getAbsolutePath()+File.separator+fileName,data,append);
    }

    /**
     * 内部保存方法
     * @param filePath
     * @param data
     * @param append
     */
    private static void save(String filePath,String data,boolean append){
        FileOutputStream fos=null;
        try{
            fos=new FileOutputStream(filePath,append);
            fos.write(data.getBytes(CHARSET));
        } catch (FileNotFoundException e) {
            Log.d(TAG,"save:文件未找到-FileNotFoundException"+e.getMessage());
        } catch (IOException e) {
            Log.d(TAG,"save:IO异常-IOException"+e.getMessage());
        }finally {
            if(fos!=null){
                try{
                    fos.close();
                } catch (IOException e) {
                    Log.d(TAG,"save:FileOutputStream close error-IOException"+e.getMessage());
                }
            }
        }
    }

    /**
     * 读取文件从/data/data/packagename/files中
     * @param fileName
     * @return
     */
    public static String getFromInnerFiles(String fileName){
        return get(innerFileDir+File.separator+fileName);
    }

    public static String getFromInnerCache(String fileName){
        return get(innerCacheDir+File.separator+fileName);
    }

    public static String getFromSDFile(String fileDir,String fileName){
        return get(sdDir+File.separator+fileDir+File.separator+fileName);
    }

    public static String getFromSDCache(String fileName){
        return get(sdCacheDir+File.separator+fileName);
    }

    /**
     * 内部读取方法
     * @param filePath
     * @return
     */
    private static String get(String filePath){
        String result=null;
        FileInputStream fis=null;
        try{
            fis=new FileInputStream(filePath);
            int len=0;
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            while((len=fis.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            byte[] targetBytes=bos.toByteArray();
            result=new String(targetBytes,CHARSET);
        } catch (IOException e) {
            Log.d(TAG,"get:IOException"+e.getMessage());
        }finally {
            if(fis!=null){
                try{
                    fis.close();
                } catch (IOException e) {
                    Log.d(TAG,"get:IOException2"+e.getMessage());
                }
            }
        }
        return result;
    }

    /**
     * 保存png图片
     * @param filePath
     * @param bitmap
     */
    public static void saveBitmap(String filePath, Bitmap bitmap){
        File file=new File(filePath);
        //创建父目录如果不存在
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        if(file.exists()){
            file.delete();
        }
        FileOutputStream fos=null;
        try{
            file.createNewFile();
            fos=new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            Log.d(TAG,"saveImage:文件未找到-FileNotFoundException"+e.getMessage());
        } catch (IOException e) {
            Log.d(TAG,"saveImage:IOException"+e.getMessage());
        }finally {
            if(fos!=null){
                try{
                    fos.close();
                } catch (IOException e) {
                    Log.d(TAG,"saveImage:IOException2"+e.getMessage());
                }
            }
        }
    }

    /**
     * 读取位图从文件中
     * @return
     */
    public static Bitmap getBitmapFromFile(String filePath){
        return BitmapFactory.decodeFile(filePath);
    }

    /**
     * 读取位图从资源中
     * @param mContext
     * @param resId
     * @return
     */
    public static Bitmap getBitmapFromResource(Context mContext,int resId){
        return BitmapFactory.decodeResource(mContext.getResources(),resId);
    }

    /**
     * 读取位图从asset目录中
     * @param mContext
     * @param fileName
     * @return
     */
    public static Bitmap getBitmapFromAssets(Context mContext,String fileName){
        AssetManager assetManager=mContext.getAssets();
        Bitmap result=null;
        InputStream is=null;
        try {
            is=assetManager.open(fileName);
            result=BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            Log.d(TAG,"getBitmapFromAssets:IOException"+e.getMessage());
        }finally{
            if(is!=null){
                try{
                    is.close();
                } catch (IOException e) {
                    Log.d(TAG,"getBitmapFromAssets:IOException2"+e.getMessage());
                }
            }
        }
        return result;
    }


}
